package tech.treec.smartlight.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.preference.PreferenceManager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.young.mylib.HttpCallback;
import com.young.mylib.OKHttpClient;
import com.young.mylib.db.dao.DeviceDao;
import com.young.mylib.db.entity.DeviceEntity;
import com.young.mylib.db.entity.DeviceRealtimeDataEntity;
import com.young.mylib.db.entity.LinkageEntity;
import com.young.mylib.utils.JsonUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import tech.treec.smartlight.R;
import tech.treec.smartlight.adapter.MyAdapter;
import tech.treec.smartlight.callback.ButtonClickCallback;
import tech.treec.smartlight.service.DeviceService;

import static tech.treec.smartlight.Constants.ACTION_LINKAGE_CONFIG_RECEIVE;
import static tech.treec.smartlight.Constants.ACTION_REQUEST_LINKAGE_CONFIG;

public class LinkageActivity extends BaseActivity {

    private final static int HANDLER_TOOLBAR_MENU = 1000, HANDLER_REF_LIST = 1001;
    private final static String TAG = "SwitchActivity";
    @BindView(R.id.my_gride_view)
    GridView gridView;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    private MsgReceiver msgReceiver;
    List<Map<String, String>> list = new ArrayList<>();
    MyAdapter adapter;
    // protected   Logger parentLogger = LogManager.getLogger(LinkageActivity.class.getName());

    //private Logger logger = parentLogger;
    @Override
    protected int setLayoutID() {
        return R.layout.activity_switch;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setSupportActionBar(toolbar);
    }

    @Override
    protected void initView() {
        toolbar.setTitle(R.string.app_name);

//        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
//        }
    }

    @Override
    protected void loadData() {
        // 设置列数
        gridView.setNumColumns(5);
        //自定义BaseAdapter适配器
        adapter = new MyAdapter(this, R.layout.switch_item, list, new ButtonClickCallback() {
            @Override
            public void onClick(String msg, int pos) {
                if (msg.equals("刷新")) {
                    requestLinkage();
                } else {
                    showDetail(list.get(pos));
                }
            }
        });
        Map map1 = new HashMap();
        map1.put("name", "刷新");
        map1.put("img", R.drawable.ic_launcher_background);
        list.add(map1);
        gridView.setAdapter(adapter);
        msgReceiver = new MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_LINKAGE_CONFIG_RECEIVE);
        registerReceiver(msgReceiver, intentFilter);
        requestLinkage();
        showProgressDialog("加载场景数据", true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "ON RESUME");

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        // if (id == R.id.action_sys) {
        //   password(id);
        //} else {
        Message msg = new Message();
        msg.what = HANDLER_TOOLBAR_MENU;
        msg.obj = id;
        //    showToast("密码错误！");
        loadHandler.sendMessage(msg);
        // }
        return super.onOptionsItemSelected(item);
    }

    private void showDetail(Map<String, String> data) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        String code = data.get("code").toString();
        LinkageEntity entity = DeviceDao.findLinkage("treeId", code);
        String roomName = data.get("name");
        roomName += entity.devices.size() > 0 ? " 联动" : " 不联动";
        builder.setTitle(roomName); // 设置对话框标题
        if (entity != null) {
            String devStr = "";
            for (Object obj : entity.devices) {
                Log.i(TAG, "deviceEntity: " + obj.toString());
                DeviceEntity deviceEntity = JsonUtils.toBean(obj.toString(), DeviceEntity.class);
                DeviceRealtimeDataEntity realtimeDataEntity = DeviceDao.findRealDataByKey("deviceId", deviceEntity.deviceId);
                if (deviceEntity != null && realtimeDataEntity != null)
                    devStr += "  \r\n" + deviceEntity.deviceName + ":" + DeviceService.getDeviceType(deviceEntity.deviceId) + "，当前值：" + realtimeDataEntity.lightStatus;
            }

            final TextView treeIdTv = new TextView(this);
            treeIdTv.setText(devStr);
            builder.setView(treeIdTv); // 将EditText添加到对话框中
        } else {
            builder.setTitle("会议室 " + data.get("name")); // 设置对话框标题
        }

        // 创建一个EditText控件，用于输入文本


//        // 设置对话框的按钮和点击事件
//        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                // 获取用户输入的文本
//
//            }
//        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); // 点击取消按钮时关闭对话框
            }
        });

        // 创建并显示对话框
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    Handler loadHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //更新界面
            if (msg.what == HANDLER_REF_LIST) {
                String str = msg.obj.toString();
                JSONObject json = JsonUtils.toJsonObject(str);
                JSONArray result = json.getJSONArray("result");
                list.clear();
                Map map1 = new HashMap();
                map1.put("name", "刷新");
                map1.put("img", R.drawable.ic_launcher_background);
                list.add(map1);
                for (Object _jo : result) {
                    JSONObject jo = JsonUtils.toJsonObject(_jo.toString());

                    Map map = new HashMap();
                    map.put("name", jo.getString("name"));
                    map.put("code", jo.getString("treeId"));
                    list.add(map);
                }

                adapter.notifyDataSetChanged();
                dismissProgressDialog("");
            }
            if (msg.what == HANDLER_TOOLBAR_MENU) {
                if ((int) msg.obj == R.id.action_dev) {
                    Log.i(TAG, "设备管理" + msg.obj);
                    Intent intent = new Intent(LinkageActivity.this, DeviceActivity.class);
                    startActivity(intent);
                }

                if ((int) msg.obj == R.id.action_sys) {
                    Log.i(TAG, "系统管理" + msg.obj);

                    Intent intent = new Intent(LinkageActivity.this, SettingsActivity.class);
                    startActivity(intent);
                }
                if ((int) msg.obj == R.id.action_log) {
                    Log.i(TAG, "应用日志" + msg.obj);
                    Intent intent = new Intent(LinkageActivity.this, LogActivity.class);
                    startActivity(intent);
                }
                if ((int) msg.obj == R.id.action_device_data) {
                    Intent intent = new Intent(LinkageActivity.this, DeviceDataActivity.class);
                    startActivity(intent);
                }

            }
        }
    };

    private void requestLinkage() {
        Log.i(TAG, "请求场景配置数据");
        JSONObject json = new JSONObject();

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        String brokerHostName = prefs.getString("serverUrl", "10.13.60.248"); // 获取默认值作为备选方案。
        String port = prefs.getString("serverPort", "28900");
        String panelId = prefs.getString("panelId", "99999");
        if (panelId.equals("99999")) {
            dismissProgressDialog("未配置服务端");
            return;
        }
        json.put("label", panelId);
        String url = "http://" + brokerHostName + ":" + port + "/api/rule/linkage/find/config";
        Log.i(TAG, "获取联动配置:" + url);
        OKHttpClient.getInstance().postJson(url, json.toJSONString(), new HttpCallback() {
            @Override
            public void onHttpResponse(String url, String msg) {
                Log.i(TAG, "获取联动配置:" + msg);


                JSONObject json = JsonUtils.toJsonObject(msg);
                String status = json.getString("status");

                if (!status.equals("ok")) {
                    Log.i(TAG, "post数据 status ok return " + status);
                    return;
                }

                JSONArray result = json.getJSONArray("result");
                if (result == null) {
                    Log.i(TAG, "post数据 result is null");
                    return;
                }

                DeviceDao.dropLinkageTable();
                DeviceDao.dropDeviceTable();
                // DeviceDao.dropDeviceDataTable();
                /**
                 * 通知界面更新联动场景
                 */
                Message message = new Message();
                message.what = HANDLER_REF_LIST;
                message.obj = msg;
                //    showToast("密码错误！");
                loadHandler.sendMessage(message);

                for (Object obj : result) {
                    LinkageEntity linkageEntity = JsonUtils.toBean(obj.toString(), LinkageEntity.class);
                    DeviceDao.replaceLinkage(linkageEntity);
                    Log.i(TAG, obj.toString());
                    // reconfirm.put(linkageEntity.treeId, 0);
                    boolean isEnabled = linkageEntity.isEnabled;
                    JSONArray devices = linkageEntity.devices;

                    if (devices != null && isEnabled) {
                        for (Object obj1 : devices) {
                            DeviceEntity dev = JsonUtils.toBean(obj1.toString(), DeviceEntity.class);
                            dev.treeId=linkageEntity.treeId;
                            dev.name=linkageEntity.name;
                            //     Log.i(TAG, "保存设备：" + dev.deviceName + ":" + dev.deviceId);
                            Log.i(TAG, "保存设备数据：" + dev.deviceId+":"+dev.treeId+":"+dev.name);
                            DeviceDao.saveDevice(dev);
                        }
                    }
                }

            }

            @Override
            public void onFail(String url, String msg) {

            }
        });
    }

    private class MsgReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "消息到达");
            try {
                String msg = intent.getStringExtra("msg");
                Message _msg = new Message();
                _msg.what = HANDLER_REF_LIST;
                _msg.obj = msg;
                loadHandler.sendMessage(_msg);
            } catch (Exception e) {
                Log.e(TAG, "MsgReceiver error: " + e.getMessage());
            }
        }
    }
}